<!DOCTYPE html>
<html>
<head lang="en">
  <meta charset="UTF-8">
  <title></title>
  <style type="text/css">
  canvas {
    display: block;
    border: 1px solid #ddd;
    margin: 0 auto;
  }
  </style>
</head>
<canvas id="canvas" width="800" height="600"></canvas>
<body>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var flag = 0;
var x = 0; // 鼠标开始移动的位置X
var y = 0; // 鼠标开始移动的位置Y
var data = [];
var dataArr = [];
var requestDatas = []; // 后台数据

$('canvas').mousemove(function(e){
    ctx.clearRect(0,0,canvas.width,canvas.height);
    redrawAll();
    if(flag == 1) { 
      drawLine(x,y,e.offsetX,e.offsetY);
    }
}).mouseup(function(e){
    flag = 1;
    x = e.offsetX;
    y = e.offsetY;
    data.push({a:x, b:y});
    requestDatas.push(x+','+y);
    if(data.length  > 1) {
      if(data.length === 2) { iteration(0)} 
      else if(data.length === 3) { iteration(1)}
      else if(data.length === 4) { iteration(2)}
      else if(data.length === 5) { iteration(3)}
    }
    if(data.length == 5) {
      flag = 2;
      data = [];
      requestDatas.pop();
    } 
});

function  iteration(num) {
  for(var i=num;i<data.length - 1;i++){
    dataArr.push({
      a: data[i].a,
      b: data[i].b,
      c: data[i+1].a,
      d: data[i+1].b
    });
  }
}

// 画线
function drawLine(x,y,c,d) {
  ctx.beginPath();
  ctx.moveTo(x,y);
  ctx.lineTo(c,d);
  ctx.stroke(); 
}

// 重绘
function redrawAll() {
  if (dataArr.length > 0 ) {
    dataArr.forEach(function (val,index) {
      drawLine(val.a, val.b, val.c, val.d);
    })
  }
}
</script>
</body>
</html>
